package com.zb.mobile.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zb.code.service.ConCodeService;
import com.zb.excel.converter.WorkConverter;
import com.zb.entity.*;
import com.zb.excel.CodeUserRegisterFieldValExtend;
import com.zb.mobile.UserGoodsDetailVo;
import com.zb.mobile.UserGoodsListVo;
import com.zb.mobile.UserModuleFeeListVo;
import com.zb.mobile.UserSpareFeeListVo;
import com.zb.mobile.user.service.ConUserMobileGoodsService;
import com.zb.result.PageUtil;
import com.zb.service.*;
import com.zb.view.ViewGoods;
import com.zb.vo.OrderCodeSelectVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author WEN
 * @Date 2023/11/6 0006
 **/
@Service
public class ConUserMobileGoodsServiceImpl implements ConUserMobileGoodsService {
    @Resource
    private ZjCodeUserRegisterService codeUserRegisterService;
    @Resource
    private ZjCodeService codeService;
    @Resource
    private ZjCodeInfoService codeInfoService;
    @Resource
    private ViewGoodsService viewGoodsService;
    @Resource
    private ZjCodeUserRegisterFieldValService codeUserRegisterFieldValService;
    @Resource
    private ZjWorkModuleService workModuleService;
    @Resource
    private ZjProductBoomService productBoomService;
    @Resource
    private ZjProductBoomChildService productBoomChildService;
    @Resource
    private ZjSpareService spareService;
    @Resource
    private ZjSpareSpecInfoService spareSpecInfoService;
    @Resource
    private ConCodeService conCodeService;

    // 我的商品 - 商品列表
    @Override
    public Map<String, Object> getGoodsList(Long userId, PageUtil pageUtil) {
        PageUtil.setPageLimitMobile(pageUtil);
        QueryWrapper<ZjCodeUserRegister> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("gmt_create");
        wrapper.select("id", "gmt_create");
        wrapper.eq("user_id", userId);
        Page<ZjCodeUserRegister> page = codeUserRegisterService.page(new Page<>(pageUtil.getPage(), pageUtil.getLimit()), wrapper);
        List<Long> codeIds = page.getRecords().stream().map(ZjCodeUserRegister::getId).toList();
        if (CollectionUtil.isEmpty(codeIds)) {
            return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), codeIds);
        }
        List<ZjCode> codeList = codeService.getUserCodeRegisterByIds(codeIds);
        List<Long> goodsIds = codeList.stream().map(ZjCode::getGoodsId).distinct().toList();
        List<Long> goodsSepcIds = codeList.stream().map(ZjCode::getGoodsSpecId).distinct().toList();
        List<ViewGoods> viewGoodsList = viewGoodsService.getByGoodsIdsAndGoodsSpecIds(goodsIds, goodsSepcIds);
        List<ZjCodeUserRegister> registerList = page.getRecords();

        List<UserGoodsListVo> voList = codeList.stream().map(code -> {
            UserGoodsListVo vo = new UserGoodsListVo();
            BeanUtil.copyProperties(code, vo);
            vo.setOverInsured(code.getWarrantyEndTime().before(new Date()));
            vo.setCode(code.getSecurityCode());
            vo.setRegisterTime(registerList.stream().filter(f -> Objects.equals(f.getId(), code.getId())).map(ZjCodeUserRegister::getGmtCreate).findFirst().orElse(null));
            viewGoodsList.stream().filter(f -> Objects.equals(1, f.getGoodsType()) && Objects.equals(f.getId(), code.getGoodsId()) && Objects.equals(f.getSpecId(), code.getGoodsSpecId()))
                    .findFirst().ifPresent(specView -> {
                vo.setGoodsBrand(specView.getBrand());
                vo.setGoodsModel(specView.getModel());
                vo.setGoodsName(specView.getName());
                vo.setGoodsSpecName(specView.getSpecName());
                vo.setImage(specView.getImage());
            });
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList.stream().sorted(Comparator.comparing(UserGoodsListVo::getRegisterTime).reversed()).toList());
    }

    // 防伪查询/电子保修卡 - 根据编码ID获取编码/电子保修卡详情
    @Override
    public UserGoodsDetailVo getGoodsDetail(Long codeId) {
        ZjCode code = codeService.getUserCodeRegisterById(codeId);
        Assert.isTrue(null != code, "商品编码ID参数["+ codeId +"]的商品编码数据不存在");

        UserGoodsDetailVo vo = new UserGoodsDetailVo();
        BeanUtil.copyProperties(code, vo);
        vo.setCode(code.getSecurityCode());
        vo.setOverInsured(null != code.getWarrantyEndTime() && code.getWarrantyEndTime().before(new Date()));

        ZjCodeUserRegister register = codeUserRegisterService.getById(codeId);
        if (null != register) {
            vo.setRegisterTime(register.getGmtCreate());
            vo.setRegister(true);

            List<CodeUserRegisterFieldValExtend> fieldVals = codeUserRegisterFieldValService.getByCodeUserRegisterId(register.getId());
            vo.setRegisterFields(fieldVals.stream().map(field -> {
                return new FieldValVo(field.getName(), field.getOptVos());
            }).toList());
        }
        ViewGoods viewGoods = viewGoodsService.getByGoodsTypeAndGoodsIdAndGoodsSpecId(code.getType(), code.getGoodsId(), code.getGoodsSpecId());
        vo.setGoodsBrand(viewGoods.getBrand());
        vo.setGoodsModel(viewGoods.getModel());
        vo.setGoodsName(viewGoods.getName());
        vo.setGoodsType(viewGoods.getType());
        vo.setGoodsSpecName(viewGoods.getSpecName());
        vo.setImage(viewGoods.getImage());
        return vo;
    }

    // 我的商品 - 商品列表详情-收费标准
    @Override
    public Map<String, Object> getModuleFeeList(Long custAccId, PageUtil pageUtil) {
        PageUtil.setPageLimitMobile(pageUtil);
        QueryWrapper<ZjWorkModule> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("gmt_update");
        wrapper.select("id", "type", "name", "warranty_day", "price");
        wrapper.eq("cust_acc_id", custAccId).eq("is_disabled", false);
        Page<ZjWorkModule> page = workModuleService.page(new Page<>(pageUtil.getPage(), pageUtil.getLimit()), wrapper);
        List<UserModuleFeeListVo> voList = page.getRecords().stream().map(mo -> {
            UserModuleFeeListVo vo = new UserModuleFeeListVo();
            BeanUtil.copyProperties(mo, vo);
            vo.setName("【" + WorkConverter.moduleTypeConverter(mo.getType()) + "】" + mo.getName());
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 我的商品 - 商品列表详情-配件价格
    @Override
    public Map<String, Object> getSpareFeeList(Long codeId, PageUtil pageUtil) {
        ZjCode code = codeService.getGoodsById(codeId);
        if (null == code || code.getType() == 2) {
            return PageUtil.pageList(pageUtil.getPage(), pageUtil.getLimit(), 0L, new ArrayList<>());
        }
        ZjProductBoom productBoom = productBoomService.getByProductIdAndProductSpecId(code.getGoodsId(), code.getGoodsSpecId());
        if (null == productBoom) {
            return PageUtil.pageList(pageUtil.getPage(), pageUtil.getLimit(), 0L, new ArrayList<>());
        }
        PageUtil.setPageLimitMobile(pageUtil);
        QueryWrapper<ZjProductBoomChild> boomChildQueryWrapper = new QueryWrapper<>();
        boomChildQueryWrapper.select("goods_id", "goods_spec_id");
        boomChildQueryWrapper.eq("product_boom_id", productBoom.getId()).eq("type", 2);
        Page<ZjProductBoomChild> page = productBoomChildService.page(new Page<>(pageUtil.getPage(), pageUtil.getLimit()), boomChildQueryWrapper);

        List<Long> spareIds = page.getRecords().stream().map(ZjProductBoomChild::getGoodsId).distinct().toList();
        List<Long> spareSpecIds = page.getRecords().stream().map(ZjProductBoomChild::getGoodsSpecId).distinct().toList();
        List<ZjSpare> spareList = spareService.listByIds(spareIds);
        List<ZjSpareSpecInfo> specInfos = spareSpecInfoService.listByIds(spareSpecIds);

        List<UserSpareFeeListVo> voList = page.getRecords().stream().map(bo -> {
            UserSpareFeeListVo vo = new UserSpareFeeListVo();
            ZjSpare spare = spareList.stream().filter(f -> Objects.equals(f.getId(), bo.getGoodsId())).findFirst().orElse(null);
            vo.setId(spare.getId());
            vo.setBrandId(spare.getBrandId());
            vo.setBrand(spare.getBrand());
            vo.setName(spare.getName());
            vo.setModel(spare.getModel());

            ZjSpareSpecInfo specInfo = specInfos.stream().filter(f -> Objects.equals(f.getId(), bo.getGoodsSpecId())).findFirst().orElse(null);
            vo.setSpecId(specInfo.getId());
            vo.setSpecName(specInfo.getName());
            vo.setPrice(specInfo.getPrice());
            vo.setOverPrice(specInfo.getOverPrice());
            vo.setImage(specInfo.getImage());
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 获取我的报单商品列表
    @Override
    public Map<String, Object> getUserOrderGoodsList(AccounLoginInfo loginInfo, PageUtil pageUtil) {
        PageUtil.setPageLimitMobile(pageUtil);
        OrderCodeSelectVo codeSelectVo = new OrderCodeSelectVo();
        codeSelectVo.setPage(pageUtil.getPage());
        codeSelectVo.setLimit(pageUtil.getLimit());
        return conCodeService.getRegisterCode(loginInfo.getCustAccId(), loginInfo.getId(), codeSelectVo);
    }
}
